package com.banciyuan.bcywebview.biz.post.write;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateNoLimteAdapter;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.biz.post.succ.PostSuccActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostItem;
import de.greenrobot.daoexample.model.WriteCover;

/**
 * Created by hy on 2015/12/31.
 */
public class WritePostActivity extends BaseActivity implements View.OnClickListener, ActionbarHelper.OnActionCallbacks {
    protected ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private TextView tv_send;
    protected PostItem postItem;
    private View viewWorkInfo;
    public static final String dongjin = "fanfic";
    public static final String undongjin = "fiction";
    protected AutoCompleteTextView et_work;
    private RadioButton rb_one;
    private RadioButton rb_two;
    protected RequestQueue mQueue;
    public static final int GO_SETRIGHTS = 1000;
    public static final int GO_SETINFO = 1001;
    protected MyProgressDialog mDialog;
    private ImageView info_label;
    private TextView info_write;
    private AutoComplateNoLimteAdapter autoComplateAdapter;
    private List<String> slist = new ArrayList<>();
    protected boolean posting = false;
    private LinearLayout llWriteCovers;
    protected List<WriteCover> writeCoverList;
    private ImageLoader imageLoader;
    protected int selectCoverIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write_post_layout);
        initArgs();
        getItem(savedInstanceState);
        initActionbar();
        initProgressbar();
        initUi();
        setItem();
        getState();
        initAction();
        getCovers();
    }

    private void getItem(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.getSerializable("postitem") != null) {
                postItem = (PostItem) savedInstanceState.getSerializable("postitem");
            }
        }
    }

    private void setItem() {
        if (!TextUtils.isEmpty(postItem.getWork())) {
            et_work.setText(postItem.getWork());
        }
        if (!TextUtils.isEmpty(postItem.getType())) {
            if (postItem.getType().equals(dongjin)) {
                rb_one.setChecked(true);
            } else {
                rb_two.setChecked(true);
            }
        }
    }

    private void getState() {
        et_work.setText(postItem.getWork());
        if (undongjin.equals(postItem.getType())) {
            rb_two.setChecked(true);
            viewWorkInfo.setVisibility(View.GONE);
            postItem.setType(undongjin);
        } else {
            rb_one.setChecked(true);
            viewWorkInfo.setVisibility(View.VISIBLE);
            postItem.setType(dongjin);
        }
    }

    @Override
    protected void initArgs() {
        imageLoader = ImageLoader.getInstance();
        Intent intent = getIntent();
        postItem = (PostItem) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        mQueue = VolleyQueue.getRquest(this);
        if (postItem.getAuthority() != null) {
            postItem.getAuthority().setSave(null);
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.post_write));
        mActionbarHelper.addItemOneText(getString(R.string.post));
        tv_send = (TextView) findViewById(R.id.base_action_bar_home_text_item);
        tv_send.setOnClickListener(this);
        mActionbarHelper.setActionCallbacks(this);
    }


    @Override
    protected void initUi() {
        et_work = (AutoCompleteTextView) findViewById(R.id.write_work);
        info_write = (TextView) findViewById(R.id.info_has_write);
        info_label = (ImageView) findViewById(R.id.info_label);

        viewWorkInfo = findViewById(R.id.ll_work_info);
        rb_one = (RadioButton) findViewById(R.id.radio_tongren);
        rb_two = (RadioButton) findViewById(R.id.radio_untongren);
        ((TextView) findViewById(R.id.info_text)).setText(getString(R.string.add_title_write));

        llWriteCovers = (LinearLayout) findViewById(R.id.ll_write_covers);

        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();
    }

    @Override
    protected void initAction() {
        findViewById(R.id.ll_rights_set).setOnClickListener(this);
        findViewById(R.id.ll_info_set).setOnClickListener(this);
        ((RadioGroup) findViewById(R.id.radio_tongjin)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio_tongren:
                        viewWorkInfo.setVisibility(View.VISIBLE);
                        postItem.setType(dongjin);
                        break;
                    case R.id.radio_untongren:
                        viewWorkInfo.setVisibility(View.GONE);
                        postItem.setType(undongjin);
                        break;
                }
            }
        });

        final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
            @Override
            public void getComplateList(String s, boolean show) {
                dealAutoJson(s, show);
            }
        };

        et_work.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!et_work.isPerformingCompletion()) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        String url = HttpUtils.BASE_URL + NovelApi.getComplete();
                        AutoComplateHelper autoHelper = new AutoComplateHelper(WritePostActivity.this, iGetAutoComplate, "work");
                        autoHelper.findServerTitle(s, true, url);
                    }
                    if (TextUtils.isEmpty(s.toString())) {
                        et_work.dismissDropDown();
                    }
                }
            }
        });
    }

    private void getCovers() {
        String url = HttpUtils.BASE_URL + NovelApi.getDefaultcover();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(WritePostActivity.this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, WritePostActivity.this)) {
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        writeCoverList = gson.fromJson(result,
                                new TypeToken<List<WriteCover>>() {
                                }.getType());
                        setCovers();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private void setCovers() {
        if (null == writeCoverList)
            return;
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        llWriteCovers.removeAllViews();
        for (int i = 0; i < writeCoverList.size(); i++) {
            View viewWriteCover = layoutInflater.inflate(R.layout.write_cover_item, llWriteCovers, false);
            if (TextUtils.isEmpty(postItem.getCover())) {
                if (i == 0) {
                    viewWriteCover.findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
                    selectCoverIndex = 0;
                }
            } else {
                if (postItem.getCover().equals(writeCoverList.get(i).getCover())) {
                    viewWriteCover.findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
                    selectCoverIndex = i;
                }
            }
            final ImageView ivWriteCover = (ImageView) viewWriteCover.findViewById(R.id.iv_write_cover);
            ivWriteCover.setTag(i);
            ivWriteCover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < llWriteCovers.getChildCount(); i++) {
                        llWriteCovers.getChildAt(i).findViewById(R.id.iv_write_cover_checked).setVisibility(View.INVISIBLE);
                    }
                    selectCoverIndex = (int) ivWriteCover.getTag();
                    llWriteCovers.getChildAt(selectCoverIndex).findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
                }
            });
            imageLoader.displayImage(writeCoverList.get(i).getPath(), ivWriteCover, ImageOptions.options);
            llWriteCovers.addView(viewWriteCover);
        }
    }

    private void dealAutoJson(String s, boolean show) {
        try {
            if (StatusCodeUtils.dealStatusCode(s, this)) {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                autoComplateAdapter = new AutoComplateNoLimteAdapter(slist, this, et_work.getText().toString());
                et_work.setAdapter(autoComplateAdapter);
            }
            if (show) {
                if (!isFinishing()) {
                    et_work.showDropDown();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void saveItem() {
        if (rb_one.isChecked()) {
            postItem.setWork(et_work.getText().toString().trim());
            postItem.setType(dongjin);
        } else {
            postItem.setWork("");
            postItem.setType(undongjin);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.ll_rights_set:
                saveItem();
                intent.setClass(this, WriteRightsActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                startActivityForResult(intent, GO_SETRIGHTS);
                break;
            case R.id.ll_info_set:
                saveItem();
                intent.setClass(this, WriteInfoActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                startActivityForResult(intent, GO_SETINFO);
                break;
            case R.id.base_action_bar_home_text_item:
                Gson gson = new Gson();
                if (valid()) {
                    mDialog.show();
                    postItem.setWork(et_work.getText().toString().trim());
                    postItem.setCover(writeCoverList.get(selectCoverIndex).getCover());
                    removeRepeatTag();
                    String json = gson.toJson(postItem);
                    postWork(json);
                }
                break;
        }
    }

    private void removeRepeatTag() {
        if (null == postItem.getOptional() || null == postItem.getOptional().getTags())
            return;
        List<String> repeatTag = new ArrayList<>();
        if (rb_one.isChecked()) {
            for (String tag : postItem.getOptional().getTags()) {
                if (tag.equals(postItem.getWork())) {
                    repeatTag.add(tag);
                    continue;
                }
                for (String character : postItem.getOptional().getCharacter()) {
                    if (tag.equals(character))
                        repeatTag.add(tag);
                }
            }
        }
        postItem.getOptional().getTags().removeAll(repeatTag);
    }

    protected boolean valid() {
        if (dongjin.equals(postItem.getType()) && TextUtils.isEmpty(et_work.getText().toString().trim())) {
            MyToast.show(this, getString(R.string.work_cant_benull));
            return false;
        }
        if (writeCoverList == null || selectCoverIndex >= writeCoverList.size()) {
            MyToast.show(this, getString(R.string.write_cover_benull));
            return false;
        }
        return true;
    }

    protected void postWork(String json) {
        if (posting) return;
        posting = true;
        String url = HttpUtils.BASE_URL + NovelApi.getNewnovel();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, json));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, WritePostActivity.this)) {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Intent detail = DetailDataHelper.createWriterDetail(WritePostActivity.this, result.getString(HttpUtils.RPID), result.getString(HttpUtils.WPID), false, false, false);
                        Intent succ = new Intent(WritePostActivity.this, PostSuccActivity.class);
                        succ.putExtra("detailtype", newDetailType(result.getString(HttpUtils.RPID), result.getString(HttpUtils.WPID)));
                        startActivities(new Intent[]{detail, succ});
                        setResult(RESULT_OK);
                        if (null != mDialog && mDialog.isShowing())
                            mDialog.dismiss();
                        saveTagInDiskMemory();
                        finish();
                    } else {
                        mDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                posting = false;
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                posting = false;
                mDialog.dismiss();
                MyToast.show(WritePostActivity.this, getString(R.string.write_post_fail));
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        requestParam.setRetryPolicy(new DefaultRetryPolicy(60000, 0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(requestParam);
    }

    private void saveTagInDiskMemory() {
        Gson gson = new Gson();
        String tagStrOriginal = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.WRITETAG, "[]");
        LinkedList<String> memoryTagList = gson.fromJson(tagStrOriginal, new TypeToken<LinkedList<String>>() {
        }.getType());
        memoryTagList.addAll(0, postItem.getOptional().getTags());
        while (memoryTagList.size() > 10) {
            memoryTagList.removeLast();
        }
        String tagStr = gson.toJson(new LinkedHashSet<>(memoryTagList));
        SPHelper.putString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.WRITETAG, tagStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GO_SETRIGHTS) {
            if (null != data)
                postItem = (PostItem) data.getSerializableExtra("postitem");
        } else if (requestCode == GO_SETINFO) {
            if (null != data) {
                postItem = (PostItem) data.getSerializableExtra("postitem");
                boolean flag = data.getBooleanExtra("change", false);
                if (flag) {
                    info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_pink));
                    info_write.setVisibility(View.VISIBLE);
                } else {
                    info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_gray));
                    info_write.setVisibility(View.GONE);
                }
            }
        }
    }

    private void finishActivity() {
        Intent intent = new Intent();
        postItem.setWork(et_work.getText().toString());
        if (null != writeCoverList && selectCoverIndex < writeCoverList.size()) {
            postItem.setCover(writeCoverList.get(selectCoverIndex).getCover());
            postItem.setPath(writeCoverList.get(selectCoverIndex).getPath());
        }
        intent.putExtra("postitem", postItem);
        setResult(RESULT_CANCELED, intent);
    }

    @Override
    public void onBackPressed() {
        finishActivity();
        super.onBackPressed();
    }

    @Override
    public void onBackClick() {
        finishActivity();
        finish();
    }

    @Override
    public void onActionClick(int id) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("postitem", postItem);
    }

    private DetailType newDetailType(String rp_id, String wp_id) {
        DetailType detailType = new DetailType();
        detailType.setRp_id(rp_id);
        detailType.setWp_id(wp_id);
        detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_WRITER);
        return detailType;
    }
}